/**
 * 时间日期工具类
 */

export default {
  // 获取指定天数前或后的日期
  getDate(n, date) {
    date = date || new Date();
    let timestamp = date.getTime();
    let newDate = new Date(timestamp + n * 24 * 3600 * 1000);
    let year = newDate.getFullYear();
    let month = newDate.getMonth() + 1;
    month = month.toString().length === 1 ? "0" + month : month;
    let day =
      newDate.getDate().toString().length === 1
        ? "0" + newDate.getDate()
        : newDate.getDate();
    const time = [year, month, day].join("-");
    return time;
  },
  // 获取今天日期
  getToday() {
    return this.getDate(0);
  },
  // 获取昨天日期
  getYesterday() {
    return this.getDate(-1);
  },
  // 获取明天日期
  getTomorrow() {
    return this.getDate(1);
  },
  // 获取前七天日期范围
  getLast7Days() {
    const startDate = this.getDate(-6);
    const endDate = this.getToday();
    return { startDate, endDate };
  },
  // 获取后七天日期范围
  getNext7Days() {
    const startDate = this.getTomorrow();
    const endDate = this.getDate(6, new Date(startDate));
    return { startDate, endDate };
  },
  // 获取本周日期范围
  getCurrentWeek() {
    let now = new Date();
    let firstDayOfWeek = new Date(
      now.setDate(now.getDate() - now.getDay() + 1)
    );
    let lastDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay() + 7));
    const startDate = this.getDate(0, firstDayOfWeek);
    const endDate = this.getDate(0, lastDayOfWeek);
    return { startDate, endDate };
  },
  // 获取本月日期范围
  getCurrentMonth() {
    let myDate = new Date();
    let tYear = myDate.getFullYear();
    let tMonth = myDate.getMonth();
    tMonth = this.doHandleZero(tMonth + 1);
    const startDate = tYear + "-" + tMonth + "-01";
    // const endDate = tYear + '-' + tMonth + '-' + new Date(tYear, tMonth, 0).getDate()
    const endDate = this.getDate(0);
    return { startDate, endDate };
  },
  // 补零函数
  doHandleZero(zero) {
    let date = zero;
    if (zero.toString().length === 1) {
      date = "0" + zero;
    }
    return date;
  },
};

/**
 * 时间戳 转  YYYY-MM-DD hh:mm:ss
 * @param timestamp
 * @returns {string}
 * @Author  Chris Lee
 */
export function formatDate(timestamp) {
  let date = new Date(timestamp);
  let Y = date.getFullYear() + "-";
  let M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
  let h =
    (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  let m =
    (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
    ":";
  let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return Y + M + D + h + m + s;
}
